/*
    Radio Battletoads Player
    Copyright (C) 2011 Jorge Suarez de Lis <yo@jorgesuarezdelis.name>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.radiobattletoads.player;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.security.PublicKey;
import java.util.Timer;
import java.lang.IllegalStateException;
import java.lang.OutOfMemoryError;

import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.location.GpsStatus.Listener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.FrameLayout.LayoutParams;

public class RadioBattletoadsActivity extends Activity {

	static public Bitmap playbm,stopbm,playbm_hover,stopbm_hover;
	float dpscale;
	Typeface font;
	static RadioBattletoadsActivity instantiatedActivity;
	public static boolean warn_mobile;
	public static int screen_size;
	private int dpsw;
	ProgressBar p;
	private Timer timer;
	
	Handler h = new Handler(){public void handleMessage(Message m){
		TextView tv2 = (TextView)RadioBattletoadsActivity.this.findViewById(R.id.now_target);
		TextView tv = (TextView)RadioBattletoadsActivity.this.findViewById(R.id.status);
		ImageView im = (ImageView)RadioBattletoadsActivity.this.findViewById(R.id.button);
		Builder builder;
		switch(m.what){
		case PLAYER_STOPPED:
			tv.setText(R.string.status_stopped);
		break;
		case PLAYER_INITIAL_BUFFERING:
			tv.setText(R.string.status_initialbuffering);
			im.setImageBitmap(stopbm);
			Toast toast = Toast.makeText(RadioBattletoadsActivity.instantiatedActivity, R.string.toast_initial, Toast.LENGTH_LONG);
        	toast.show();
			break;
		case PLAYER_CHECKINGCONNECTION:
			tv.setText(R.string.status_checking);
			im.setImageBitmap(stopbm);
			break;
		case PLAYER_BUFFERING:
			im.setImageBitmap(stopbm);
			tv.setText(R.string.status_buffering);
			break;
		case PLAYER_PLAYING:
			im.setImageBitmap(stopbm);
			tv.setText(R.string.status_playing);
			break;
		case PLAYER_IOEXCEPTION:
			tv.setText(R.string.status_dropped);
			im.setImageBitmap(playbm);
			builder = new AlertDialog.Builder(RadioBattletoadsActivity.instantiatedActivity);
	  	    builder.setTitle(R.string.ioexception_title);
	  	    builder.setMessage(R.string.ioexception_body);
	  	    builder.setNeutralButton(android.R.string.ok, null);
	  	    builder.setPositiveButton(R.string.ioexception_button, new OpenTheBrowser());
	  	    builder.show();
			break;
		case PLAYER_NOPLAYLIST:
			tv.setText(R.string.status_dropped);
			im.setImageBitmap(playbm);
			builder = new AlertDialog.Builder(RadioBattletoadsActivity.instantiatedActivity);
	  	    builder.setTitle(R.string.noplaylist_title);
	  	    builder.setMessage(R.string.noplaylist_body);
	  	    builder.setNeutralButton(android.R.string.ok, null);
	  	    builder.show();
			break;
		case PLAYER_DROPPED:
			tv.setText(R.string.status_dropped);
			im.setImageBitmap(playbm);
			break;
		case UPDATE_NOW:
			if(!tv2.getText().equals(m.getData().getString("now")))
				tv2.setText(m.getData().getString("now"));
			p = (ProgressBar) RadioBattletoadsActivity.this.findViewById(R.id.now_progressbar);
			if(p!=null) p.setVisibility(View.GONE);
			break;
		case UPDATE_NOW_FAILED:
			tv2.setText(R.string.error);
			p = (ProgressBar) RadioBattletoadsActivity.this.findViewById(R.id.now_progressbar);
			if(p!=null) p.setVisibility(View.GONE);
			break;
		case UPDATE_SCHEDULE:
		case UPDATE_SCHEDULE_FAILED:
			int i;
			/* Get schedule and complete with music */
			String[] sch = m.getData().getStringArray("schedule");
			if(sch == null) sch = new String[3];
			for(i=0;sch[i]!=null;i++);
			if(((i-1)>=0) && sch[i-1]!="Resto#[MI]Música Ininterrumpida"){
				sch[i]="Resto#[MI]Música Ininterrumpida";
				sch[i+1]=null;
			}
			else sch[i]=null;
			/* Remove old elements */
			LinearLayout ly = (LinearLayout)RadioBattletoadsActivity.this.findViewById(R.id.schedule_layout);
			if(ly.getChildCount()>0) ly.removeAllViews();
			/* Add new elements */
			for(i=0;sch[i]!=null;i++){
				String current_schedule = sch[i];
				String current_schedule_time = current_schedule.substring(0,current_schedule.indexOf("#"));
				String current_schedule_title = current_schedule.substring(current_schedule.indexOf("#")+1);
				LinearLayout lyn = new LinearLayout(RadioBattletoadsActivity.this);
				TextView tvtime = new TextView(RadioBattletoadsActivity.this);
				tvtime.setTextColor(R.color.Grisaco);
				tvtime.setText(current_schedule_time);
				tvtime.setTypeface(font);
				tvtime.setSingleLine();
				tvtime.setWidth(applyscale(55,false));
				tvtime.setPadding(0,0,applyscale(3,false),0);
				tvtime.setGravity(Gravity.RIGHT);
				tvtime.setTextSize(applyscale(9,true));
				TextView tvtitle = new TextView(RadioBattletoadsActivity.this);
				tvtitle.setTextColor(Color.BLACK);
				tvtitle.setText(current_schedule_title);
				tvtitle.setTypeface(font);
				tvtitle.setSingleLine();
				tvtitle.setEllipsize(TruncateAt.END);
				tvtitle.setTextSize(applyscale(12,true));
				lyn.addView(tvtime);
				lyn.addView(tvtitle);
				ly.addView(lyn);
			}
			p = (ProgressBar) RadioBattletoadsActivity.this.findViewById(R.id.schedule_progressbar);
			if(p!=null) p.setVisibility(View.GONE);
			break;
		case GOING_TO_UPDATE_SCHEDULE:
			p = (ProgressBar) RadioBattletoadsActivity.this.findViewById(R.id.schedule_progressbar);
			if(p!=null) p.setVisibility(View.VISIBLE);
			break;
		case GOING_TO_UPDATE_NOW:
			p = (ProgressBar) RadioBattletoadsActivity.this.findViewById(R.id.now_progressbar);
			if(p!=null) p.setVisibility(View.VISIBLE);
			break;
		case PLAYER_BLOCKED:
			PlayerService.showDialog(PlayerService.DIALOG_BLOCKED);
			tv.setText(R.string.status_dropped);
			im.setImageBitmap(playbm);
		break;
		}
		
	}};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.item1:
	    	Builder builder = new AlertDialog.Builder(this);
	  	    builder.setTitle(R.string.about_title);
	  	    builder.setMessage(R.string.about_body);
	  	    builder.setNeutralButton(android.R.string.ok, null);
	  	    builder.show();
	        return true;
	    case R.id.item2:
	    	Intent intent = new Intent(RadioBattletoadsActivity.this, RadioBattletoadsPreferencesActivity.class);
	    	RadioBattletoadsActivity.this.startActivity(intent);
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	public final static int GOING_TO_UPDATE_NOW = 1;
	public final static int GOING_TO_UPDATE_SCHEDULE = 2;
	public final static int UPDATE_NOW = 3;
	public final static int UPDATE_NOW_FAILED = 4;
	public final static int UPDATE_SCHEDULE = 5;
	public final static int UPDATE_SCHEDULE_FAILED = 6;
	public final static int PLAYER_PLAYING = 7;
	public final static int PLAYER_BUFFERING = 8;
	public final static int PLAYER_STOPPED = 9;
	public final static int PLAYER_DROPPED = 10;
	public final static int PLAYER_BLOCKED = 15;
	public final static int PLAYER_CHECKINGCONNECTION = 14;
	public final static int PLAYER_INITIAL_BUFFERING = 11;
	public final static int PLAYER_IOEXCEPTION = 12;
	public final static int PLAYER_NOPLAYLIST = 13;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	this.instantiatedActivity = this;

    	/* Init layout */
    	super.onCreate(savedInstanceState);
    	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  	    setContentView(R.layout.main);

  	    /* Load bitmaps */
		playbm = BitmapFactory.decodeResource(this.getResources(), R.drawable.play);
		stopbm = BitmapFactory.decodeResource(this.getResources(), R.drawable.stop);
		playbm_hover = BitmapFactory.decodeResource(this.getResources(), R.drawable.play_hover);
		stopbm_hover = BitmapFactory.decodeResource(this.getResources(), R.drawable.stop_hover);

  	    /* Initialize layout */
  	    this.dpscale = this.getResources().getDisplayMetrics().density;
  	    Configuration conf = this.getResources().getConfiguration();
  	    
  	    /* Get smallest width factor of the screen */
  	    this.dpsw = (int) ((this.getResources().getDisplayMetrics().widthPixels>this.getResources().getDisplayMetrics().heightPixels)?this.getResources().getDisplayMetrics().heightPixels:this.getResources().getDisplayMetrics().widthPixels);
  	    
  	    /* Set custom font */
  	    font = Typeface.createFromAsset(this.getAssets(), "fonts/Coustard-Regular.ttf"); 
  	    TextView tv = (TextView)this.findViewById(R.id.now);
  	    tv.setTypeface(font);
  	    tv = (TextView)this.findViewById(R.id.now_target);
  	    tv.setTypeface(font);
  	    tv = (TextView)this.findViewById(R.id.status);
	    tv.setTypeface(font);
	    tv = (TextView)this.findViewById(R.id.schedule);
	    tv.setTypeface(font);
	    tv = (TextView)this.findViewById(R.id.schedule_loading);
	    tv.setTypeface(font);
	    
	    /* Ensure marquee has the focus */
	    tv = (TextView)this.findViewById(R.id.now_target);
	    tv.setSelected(true);
	    tv = (TextView)this.findViewById(R.id.status);
	    tv.setSelected(true);
 	    
  	    /* Update now playing and schedule */
	    timer = new Timer();
		UpdateNowPlaying.firstrun=true;
		timer.schedule(new UpdateNowPlaying(),0, 20000);
		UpdateSchedule.firstrun=true;
		timer.schedule(new UpdateSchedule(),0, 240000);
        
        /* Reflect real status from service */
        PlayButton.updateButtonAndStatus();
        
        /* Load preferences */
        RadioBattletoadsPreferencesActivity.reloadPreferences();
        
        /* Set button callback */
        PlayButton playbutton = new PlayButton();
        this.findViewById(R.id.button).setOnClickListener(playbutton);
        this.findViewById(R.id.button).setOnTouchListener(playbutton);
        
        /* Delete notifications if they are still there (e.g. the application crashed) */
        if(PlayerService.player_status==RadioBattletoadsActivity.PLAYER_STOPPED||
        		PlayerService.player_status==RadioBattletoadsActivity.PLAYER_DROPPED)
        	NotificationManager.removeAllNotifications(this);
        
        /* Show again dialogs if they were being showed */
        PlayerService.showDialog(PlayerService.DIALOG_PREVIOUS);
        
    }
    
    public void onDestroy(){
    	super.onDestroy();
    	this.instantiatedActivity = null;
    	if(this.timer!=null){
    		this.timer.cancel();
    		this.timer.purge();
    	}
    }
    
    private int applyscale(int p,boolean noapplydp){
    	float dps;
    	if(noapplydp) dps = 1;
    	else dps = dpscale;
    	if(this.dpsw>=600) return (int) ((p * dps * 3) + 0.5); // Scale for tablets
    	else return (int) ((p * dps) + 0.5); // Normal scale
	}
    
}
